package org.tinygame.herostory.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import org.tinygame.herostory.BroadCaster;
import org.tinygame.herostory.mode.MoveState;
import org.tinygame.herostory.mode.User;
import org.tinygame.herostory.mode.UserManager;
import org.tinygame.herostory.msg.GameMsgProtocol;

public class UserMoveToCmdHandler implements ICmdHandler<GameMsgProtocol.UserMoveToCmd> {

    /**
     * 处理英雄移动
     * @param ctx
     * @param msg
     */
    @Override
    public void handler(ChannelHandlerContext ctx, GameMsgProtocol.UserMoveToCmd msg) {

        if(null == msg || null == ctx){
            return;
        }

        //获取用户id
        Integer userId = (Integer) ctx.channel().attr(AttributeKey.valueOf("userId")).get();

        if(null == userId){
            return;
        }

        //获取移动用户
        User user = UserManager.getUserById(userId);

        if(null == user){
            return;
        }

        //获取移动状态
        MoveState moveState = user.getMoveState();
        //设置位置和时间
        moveState.setFromPosX(msg.getMoveFromPosX());
        moveState.setFromPosY(msg.getMoveFromPosY());
        moveState.setToPosX(msg.getMoveToPosX());
        moveState.setToPosY(msg.getMoveToPosY());
        moveState.setStartTime(System.currentTimeMillis());//移动开始时间，以服务器为准

        GameMsgProtocol.UserMoveToCmd cmd = msg;

        GameMsgProtocol.UserMoveToResult.Builder resultBuilder = GameMsgProtocol.UserMoveToResult.newBuilder();
        resultBuilder.setMoveUserId(userId);
        resultBuilder.setMoveFromPosX(moveState.getFromPosX());
        resultBuilder.setMoveFromPosY(moveState.getFromPosY());
        resultBuilder.setMoveToPosX(moveState.getToPosX());
        resultBuilder.setMoveToPosY(moveState.getToPosY());
        resultBuilder.setMoveStartTime(moveState.getStartTime());

        //群发移动信息
        GameMsgProtocol.UserMoveToResult newResult = resultBuilder.build();
        BroadCaster.broadCaster(newResult);
    }
}
